import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:gif_inspector/bean/frame_bean.dart';
import 'package:gif_inspector/gif_inspector.dart';
import 'package:image_picker/image_picker.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});
  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  List<FrameBean> frames = [];
  final ImagePicker _imagePicker = ImagePicker();

  void _pickImg() async{
    XFile? file = await _imagePicker.pickImage(source: ImageSource.gallery);
    if(file != null){
      Uint8List data = await file.readAsBytes();
      List<FrameBean> temp = await GifInspector.readGif(data);
      setState(() {
        frames = temp;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: Wrap(
        children: frames.map((e) => _buildImage(context, e)).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _pickImg,
        tooltip: 'Pick',
        child: const Icon(Icons.image),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
  
  Widget _buildImage(BuildContext context, FrameBean bean) {
    Size size = MediaQuery.of(context).size;
    return SizedBox(
      width: size.width / 3,
      height: size.width / 3,
      child: Center(
        child: Column(
          children: [
            Image.memory(bean.data),
            Text('${bean.duration.inMilliseconds}ms')
          ],
        ),
      ),
    );
  } 
}
